package serverkeymaker;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.KeyPair;

import client.data.KeyPairPair;

import packets.client.PublicKeyPair;


import sun.misc.BASE64Encoder;
import encription.SecurityHandler;

/**
 * a small class which generates encryption/signing keys for a server
 * creates 2 files.
 * first file - "serverfile" containing the server's public and private keys (for the server)
 * second file - "serverpublickeys" containing the server's public keys (for the clients)
 * the files are encoded using base64
 */
public class KeyMaker {

	/**
	 * produces the "serverfile", containing the server's private and public keys
	 * @param keys the keys to write to the file
	 * 
	 */
	private static void writeData(KeyPairPair keys){
		String filename = "./serverfile";
		BASE64Encoder e = new BASE64Encoder();
		try {
			ByteArrayOutputStream bais = new ByteArrayOutputStream();
			ObjectOutputStream ois = new ObjectOutputStream(bais);
			ois.writeObject(keys);
			byte[] bytes = bais.toByteArray();
			FileOutputStream fis = new FileOutputStream(filename);
			e.encodeBuffer(bytes, fis);
		} catch (IOException e1) {
			System.out.println("Error writing server keys to file");
			//e1.printStackTrace();
		}
	}
	
	/**
	 * produces the "serverpublickeys" file, containing the server's private and public keys
	 * @param keys the keys to write to the file
	 * 
	 */
	private static void writeData(PublicKeyPair keys){
		String filename = "./serverpublickeys";
		BASE64Encoder e = new BASE64Encoder();
		try {
			ByteArrayOutputStream bais = new ByteArrayOutputStream();
			ObjectOutputStream ois = new ObjectOutputStream(bais);
			ois.writeObject(keys);
			byte[] bytes = bais.toByteArray();
			FileOutputStream fis = new FileOutputStream(filename);
			e.encodeBuffer(bytes, fis);
		} catch (IOException e1) {
			System.out.println("Error writing server keys to file");
			//e1.printStackTrace();
		}
	}

	/**
	 * main method to run this class
	 * @param args
	 */
	public static void main(String[] args){
		try{
		KeyPair serverKey = SecurityHandler.makeKey();
		KeyPair signatureKey = SecurityHandler.makeKey();
		KeyPairPair keys = new KeyPairPair(serverKey, signatureKey);
		writeData(keys);
		writeData(new PublicKeyPair(serverKey.getPublic(),signatureKey.getPublic()));
		} catch (Exception e){
			System.out.println("couldnt write to file");
			//e.printStackTrace();
		}
	}
}

